package com.longcai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.sys.SysRoleUser;
import com.longcai.entity.sys.SysUser;
import com.longcai.mapper.SysRoleUserMapper;
import com.longcai.mapper.SysUserMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.SysUserService;
import com.longcai.vo.SysUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZJ
 * @since 2019-03-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser getUser(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public PageTableResponse sysUserlistPage(SysUser sysUser, PageHelper pageHelper) {

        Page<SysUser> page = new Page<SysUser>(pageHelper.getStart(), pageHelper.getLength());
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(sysUser.getUsername())) {
            queryWrapper.eq("username", sysUser.getUsername());
        }
        if (!StringUtils.isEmpty(sysUser.getNickname())) {
            queryWrapper.eq("nickname", sysUser.getNickname());
        }
        if (!StringUtils.isEmpty(sysUser.getStatus())) {
            queryWrapper.eq("status", sysUser.getStatus());
        }

        IPage<SysUser> sysUserIPage = this.sysUserMapper.selectPage(page, queryWrapper);
        PageTableResponse pageTableResponse = new PageTableResponse(sysUserIPage.getTotal(), sysUserIPage.getTotal(), sysUserIPage.getRecords());

        return pageTableResponse;
    }

    @Override
    public ApiResult<SysUser> getSysUserById(Long id) {
        SysUser sysUser = this.sysUserMapper.selectById(id);
        return ApiResult.success(sysUser);
    }

    /**
     * 修改用户信息
     *
     * @param sysUserVo
     * @return
     */
    @Override
    @Transactional
    public SysUser updateSysUser(SysUserVo sysUserVo) {
        sysUserMapper.updateById(sysUserVo);
        saveSysUserRoles(sysUserVo.getId(), sysUserVo.getRoleId());
        return sysUserVo;
    }

    @Override
    public SysUser saveSysUser(SysUserVo sysUserVo) {
        SysUser sysUser = sysUserVo;
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUser.setStatus(SysUser.Status.VALID);

        this.sysUserMapper.insert(sysUser);
        this.saveSysUserRoles(sysUser.getId(), sysUserVo.getRoleId());
        logger.debug("新增用户{}", sysUser.getUsername());

        return sysUser;
    }

    /**
     * 修改密码
     * @param sysUser
     * @param newPassword
     * @return
     */
    @Override
    public ApiResult<SysUser> updatePassword(SysUser sysUser,String newPassword) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", sysUser.getUsername());

        SysUser user = this.sysUserMapper.selectOne(queryWrapper);
        if (user == null)
            return ApiResult.fail("密码错误");
        //解密密码进行比较
        boolean matches = passwordEncoder.matches(sysUser.getPassword(), user.getPassword());
        if(!matches)
        	return ApiResult.fail("输入旧密码错误");
        user.setPassword(passwordEncoder.encode(newPassword));
        sysUserMapper.updateById(user);
        return ApiResult.success();
    }

    /**
     * 添加角色中间表
     *
     * @param userId
     * @param roleId
     */
    private void saveSysUserRoles(Integer userId, Integer roleId) {
        if (roleId != null) {
            sysRoleUserMapper.deleteById(userId);
            if (roleId != null) {
                SysRoleUser sysRoleUser = new SysRoleUser(userId, roleId);

                sysRoleUserMapper.insert(sysRoleUser);
            }
        }
    }
}
